package com.mysql.backup;

import java.io.File;
import java.io.IOException;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Date;

import com.mysql.opt.Operator;

import system.mysql_connector.MySQL_Connector;

import common.FileControlSet;


public class DataBaseBackup4MySQL {
	private DataBaseBackupFactory fac;
	private String encoding = "UTF-8";
	private String savePath = "";
	
	public DataBaseBackup4MySQL(String encoding,File backupSaveDir) throws BackupException{				
		if(backupSaveDir!=null){
			if(!backupSaveDir.exists() || !backupSaveDir.isDirectory()){
				backupSaveDir.mkdirs();
			}			
			this.encoding = encoding;
			this.savePath = backupSaveDir.getAbsolutePath();
			this.fac = new DataBaseBackupFactory(this.encoding);
		}else{
			throw new BackupException("The backupSaveDir can not be null");
		}
	}	
	
	/**
	 * Save backup as default 
	 * @throws BackupException 
	 * @throws IOException 
	 */
	public void backupAll() throws BackupException, IOException{
		this.fac.doAllBack(this.savePath);
	}
	
	public void backupViews() throws BackupException{
		this.fac.doBackView(this.savePath);
	}
	
	public void backupTables() throws BackupException{
		this.fac.doBackTb(this.savePath);
	}
	
	public void backupTriggers() throws BackupException{
		this.fac.doBackTrig(this.savePath);
	}
	
	public void backupProceduresAndFunctions() throws BackupException{
		this.fac.doBackProc(this.savePath);
	}
	
	public void executeObjJdbcSqlBackupFiles(String savePath, boolean isIgnoreError){
		FileControlSet fcs = new FileControlSet();
		
	}
	
	public void executeObjJdbcSqlBackupFiles(File[] files, boolean isIgnoreError){
		int ErrorCnt = 0;
		int ExecuteCnt = 0;
		Long beginTime = new Date().getTime();
		for(int i=0;i<files.length;i++){
			int[] re = this.fac.executeBackupSql(files[i].getAbsolutePath(), this.encoding, isIgnoreError);
			ExecuteCnt += re[0];
			ErrorCnt += re[1];			
			if(ErrorCnt!=0 && !isIgnoreError){
				break;
			}
		}
		Long endTime = new Date().getTime();
		String result = this.genResult(true, ExecuteCnt, ErrorCnt, endTime, beginTime);
		System.out.println(result);
	}
	
	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	private String genResult(boolean isFinish, int TotalSqls, int ErrorCnt, Long endTime, Long beginTime){
		String stateMent = "";
		stateMent += "################## Obj-jdbc-r ######################" + Operator.nextline;
		stateMent += (isFinish)?("Finish ALL!"):("Not Finish") + Operator.nextline;
		stateMent += "Total SQLs: " + TotalSqls+ Operator.nextline;
		stateMent += "Error Count: " + ErrorCnt+ Operator.nextline;
		stateMent += "Cost: " + (endTime - beginTime) + "ms" + Operator.nextline;
		stateMent += "####################################################" + Operator.nextline;
		return stateMent;
	}
	
}
